﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using WinFormStore.ScannerSerialPro;
using WinFormStore.实体库;
using WinFormStore.数据层;
using WinFormStore.通信层;
using MessageBox = System.Windows.Forms.MessageBox;



namespace WinFormStore.Erp
{
    public partial class FrmCash : Form
    {
        //配置文件路径
        public string path;
        //配置服务对象
        public ScannerInfoService infoService;
        //配置实体对象
        public ScannerInfo scannerInfo;
        public ScannerComService comService;//声明数据层对象

        public FrmCash(string _path, ScannerInfoService _infoService, ScannerInfo _scannerInfo)
        {
            InitializeComponent();
            this.path = _path;
            this.infoService = _infoService;
            this.scannerInfo = _scannerInfo;
        }
        private List<string> codeList = new List<string>();//所有条码集合
        private void ComService_CodeReceived(string code)
        {
            //空码判断
            if (code.Length == 0)
            {
                AddLog("条形码为空");
                return;
            }
            //已存在判断
            if (codeList.Contains(code))
            {
                this.Invoke(new EventHandler(delegate
                {
                    UpdateView();
                }));

            }
            //如果有需要，可以添加其他特殊判断...
            //正确读取显示
            codeList.Add(code);
            AddLog(code);
        }
        private void AddLog(string message)
        {
            if (this.txtBarCode.InvokeRequired)
            {
                this.txtBarCode.Invoke(new Action<string>(AddLog), message);
            }
            else
            {
                this.txtBarCode.Text = message;
            }
        }
        private void FrmCash_Load(object sender, EventArgs e)
        {
            BindCtrol();
            comService = new ScannerComService();//实例化数据层对象
            comService.Connect(scannerInfo);
            comService.CodeReceived += ComService_CodeReceived;
        }
        private void BindCtrol()
        {
            //绑定导购员下拉框
            string sql = "select * from SalesMan where Role='导购员'";
            DBHelper.PrepareSql(sql);
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery();
            DataRow dr = dt.NewRow();
            dr["SalesmanID"] = "0";
            dr["SalesmanName"] = "--请选择--";
            dt.Rows.InsertAt(dr, 0);
            this.cmbDaogou.DataSource = dt;
            this.cmbDaogou.ValueMember = "SalesmanID";
            this.cmbDaogou.DisplayMember = "SalesmanName";
            //流水号
            this.lblRc.Text = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            //绑定总金额
            this.lblTotal.Text = "共:￥0.00元";
            //绑定商品数量
            this.lblCount.Text = "商品数量:0";
            //绑定收银员
            this.lblshouyinyuan.Text = "收银员:" + LoginConfig.SalesManName;
            //绑定应收，实收，找零文本框
            this.txtYingshou.Text = "0.00";
            this.txtFact.Text = "0.00";
            this.txtches.Text = "0.00";
        }
        #region 当商品列表发生改变的时候更新其他控件的值
        private void UpdateInfo()
        {
            double sumMoney = 0;
            int sumCount = 0;
            foreach (ListViewItem good in this.lvGoods.Items)
            {
                sumMoney += int.Parse(good.SubItems[6].Text) * double.Parse(good.SubItems[5].Text);
                sumCount += int.Parse(good.SubItems[6].Text);
            }
            this.lblTotal.Text = "共:￥" + sumMoney.ToString("F2") + "元";
            this.lblCount.Text = "商品数量:" + sumCount;
            //绑定应收，实收，找零文本框
            this.txtYingshou.Text = sumMoney.ToString("F2");
            this.txtFact.Text = "0.00";
            this.txtches.Text = (double.Parse(this.txtFact.Text) - double.Parse(this.txtYingshou.Text)).ToString("F2");
        }
        private void UpdateView()
        {
            foreach (ListViewItem good in this.lvGoods.Items)
            {
                if (this.txtBarCode.Text.Equals(good.Text))
                {
                    int goodCount = int.Parse(good.SubItems[6].Text);
                    goodCount++;
                    good.SubItems[6].Text = goodCount.ToString();
                    //更新界面其它控件
                    UpdateInfo();
                    return;
                }
            }
            string sql = "select * from Goods inner join [Type] on Goods.TypeID=[Type].TypeID where BarCode=@BarCode";
            DBHelper.PrepareSql(sql);
            DBHelper.SetParameter("BarCode", this.txtBarCode.Text);
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery();
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("没有找到该商品!");
                return;
            }
            ListViewItem item = new ListViewItem(dt.Rows[0]["BarCode"].ToString());
            item.SubItems.Add(dt.Rows[0]["GoodsName"].ToString());
            item.SubItems.Add(dt.Rows[0]["TypeName"].ToString());
            double salePrice = double.Parse(dt.Rows[0]["SalePrice"].ToString());
            double discount = double.Parse(dt.Rows[0]["Discount"].ToString());
            item.SubItems.Add(salePrice.ToString());
            item.SubItems.Add(discount.ToString());
            item.SubItems.Add((salePrice * discount).ToString("F2"));
            item.SubItems.Add("1");
            item.SubItems.Add(dt.Rows[0]["GoodsID"].ToString());
            this.lvGoods.Items.Add(item);
            UpdateInfo();
        }
        #endregion
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            int keyCode = (int)e.KeyChar;
            if (keyCode != 13)//判断不是回车键退出方法
            {
                return;
            }
            UpdateView();
        }
        private void lvGoods_KeyPress(object sender, KeyPressEventArgs e)
        {
            //+43  -45 backspace8
            if (this.lvGoods.SelectedItems.Count == 0)
            {
                return;
            }
            int keyCode = (int)e.KeyChar;
            if (keyCode == 43)//+
            {
                int goodCount = int.Parse(this.lvGoods.SelectedItems[0].SubItems[6].Text);
                goodCount++;
                this.lvGoods.SelectedItems[0].SubItems[6].Text = goodCount.ToString();
            }
            if (keyCode == 45)//-
            {
                int goodCount = int.Parse(this.lvGoods.SelectedItems[0].SubItems[6].Text);
                if (goodCount == 1)
                {
                    return;
                }
                goodCount--;
                this.lvGoods.SelectedItems[0].SubItems[6].Text = goodCount.ToString();
            }
            if (keyCode == 8)//backspace
            {
                this.lvGoods.SelectedItems[0].Remove();
            }
            UpdateInfo();
        }
        //private void txtFact_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    int keyCode = (int)e.KeyChar;
        //    if (keyCode != 13)
        //    {
        //        return;
        //    }
        //    this.txtches.Text = (double.Parse(this.txtFact.Text) - double.Parse(this.txtYingshou.Text)).ToString("F2");
        //}
        private void btnjiesuan_Click(object sender, EventArgs e)
        {
            if (lvGoods.Items.Count > 0 && cmbDaogou.SelectedIndex != 0 )
            {
                double fact = Convert.ToDouble(txtFact.Text);
                double yingshou = Convert.ToDouble(txtYingshou.Text);
                if (fact-yingshou>=0)
                {
                    //账单
                    string sql = "insert into Sales(ReceiptsCode,SalesDate,AllMoney,SalesmanID,CashierID) values(@ReceiptsCode,getdate(),@AllMoney,@SalesmanID,@CashierID) select @@identity";
                    DBHelper.PrepareSql(sql);
                    DBHelper.SetParameter("ReceiptsCode", this.lblRc.Text);
                    DBHelper.SetParameter("AllMoney", this.txtYingshou.Text);
                    DBHelper.SetParameter("SalesmanID", this.cmbDaogou.SelectedValue.ToString());
                    DBHelper.SetParameter("CashierID", LoginConfig.SalesManID);
                    int salesId = int.Parse(DBHelper.ExecuteScalar().ToString());
                    //明细表
                    foreach (ListViewItem good in this.lvGoods.Items)
                    {
                        sql = "insert into SalesDetail(SalesID,GoodsID,Quantity,GoodsMoney) values(@SalesID,@GoodsID,@Quantity,@GoodsMoney)";
                        DBHelper.PrepareSql(sql);
                        DBHelper.SetParameter("SalesID", salesId);
                        DBHelper.SetParameter("GoodsID", good.SubItems[7].Text);
                        DBHelper.SetParameter("Quantity", good.SubItems[6].Text);
                        DBHelper.SetParameter("GoodsMoney", good.SubItems[5].Text);
                        DBHelper.ExecuteNonQuery();
                    }
                    MessageBox.Show("结算成功！");
                    this.txtBarCode.Text = "";
                    this.lvGoods.Items.Clear();
                    BindCtrol();
                }
                else
                {
                    MessageBox.Show("应收金额不能大于实收金额");
                }
            }
            else
            {
                MessageBox.Show("结算失败！请检查商品列表和导购员选择。");
            }
        }
        private void FrmCash_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.comService.DisConn();
            this.Dispose();
            this.Close();
        }

        private void txtFact_TextChanged(object sender, EventArgs e)
        {
            this.txtches.Text = (double.Parse(this.txtFact.Text) - double.Parse(this.txtYingshou.Text)).ToString("F2");
        }
    }
}
